package com.kgc.sportscircle.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.kgc.sportscircle.pojo.Sportsuser;
import com.kgc.sportscircle.redis.LoginPrefix;
import com.kgc.sportscircle.redis.RedisService;
import com.kgc.sportscircle.service.SportsuserService;
import com.kgc.sportscircle.utils.PasswordEncrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@RestController
public class LoginController {
    @Reference(version ="1.11")
    private SportsuserService sportsuserService;
    @Autowired
    RedisService redisService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @RequestMapping("/selectUserByMobile.do")
    public Map selectUserByMobile(String mobile, String password, HttpServletResponse response){
        Map result = new HashMap();
        result.put("flag",false);
        if (!mobile.matches("^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\\d{8}$")){
            result.put("msg","手机格式不对");
            return result;
        }
        if (!password.matches("^[a-zA-Z]\\w{5,17}$")){
            result.put("msg","密码要以字母开头，长度在6~18之间，只能包含字母、数字和下划线");
            return result;
        }
        Sportsuser sportsuser = sportsuserService.selectUserByMobile(mobile);
        if (sportsuser==null){
            result.put("msg","手机号不存在");
            return result;
        }
        String pwd = sportsuser.getPassword();
        //进行md5加密之后判断
        if (pwd.equals(PasswordEncrypt.encodeByMd5(password))){
            //生成令牌，保存在cookie
            Cookie cookie = new Cookie("token",mobile);
            response.addCookie(cookie);
            //将令牌和用户信息保存在redis
            redisService.set(LoginPrefix.getLoginList,mobile,sportsuser);
            //stringRedisTemplate.opsForValue().set("loginuser:"+token,user);
            result.put("flag",true);
            result.put("msg","登陆成功");
        }
        return result;
    }
}
